//logs.js
//var util = require('../../utils/util.js')
var app = getApp()
Page({
  data: {
    feed: [],
    feed_length: 0,
    motto: 'Hello World',
    userInfo: {},
    navTab:['动态','关注','粉丝'],
    currentNavtab:0,
    commentfocus: false,
    followman:[],
    fans:[]
  },
  //事件处理函数
  onChangeItem: function(e) {
   this.setData({
     currentNavtab: e.detail.current
   });
  },
  onLoad: function (options) {
    console.log('onLoad')
    var that = this
    wx.setNavigationBarTitle({
      title: options.nickname
    })
    this.setData({
      userInfo:{nickName:options.nickname,headImg:options.headimg,unionid:options.unionid}
    });
      that.getData();
      that.getFollowData();
      that.getFansData();

  },
  refresh: function (e) {
    var unionid = e.currentTarget.dataset.unionid;
    var headimg = e.currentTarget.dataset.headimg;
    var nickname = e.currentTarget.dataset.nickname;
    console.log('refresh')
    wx.setNavigationBarTitle({
      title: nickname
    })
    var that = this
    this.setData({
      userInfo: { nickName: nickname, headImg: headimg, unionid: unionid }
    });
    that.getData();
    that.getFollowData();
    that.getFansData();
  },
  switchTab: function (e) {
    this.setData({
      currentNavtab: e.currentTarget.dataset.idx
    });
    
  },
  onPullDownRefresh:function(){
    console.log("onPullDownRefresh");
    if (this.data.currentNavtab == 0){
      this.upper();
    } else if(this.data.currentNavtab == 1){
      this.followmanupper();
    } else if (this.data.currentNavtab == 2) {
      this.fansupper();
    }
  },

  upper: function () {
    
    console.log("upper");
    wx.showNavigationBarLoading()
    wx.showLoading({
      title: "刷新中"
    });
    this.getData(function () {
      wx.hideLoading();
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 2000
      });
      wx.hideNavigationBarLoading(); wx.stopPullDownRefresh();
    });
  },
  lower: function (e) {
    wx.showNavigationBarLoading();
    var that = this;
    setTimeout(function () { wx.hideNavigationBarLoading(); that.nextLoad(); }, 1000);
    console.log("lower")
  },
  followmanupper: function () {
    wx.showNavigationBarLoading()
    wx.showLoading({
      title: "刷新中"
    });
    this.getFollowData(function () {
      wx.hideLoading();
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 2000
      });
      wx.hideNavigationBarLoading(); wx.stopPullDownRefresh();
    });

    console.log("fansupper");

  },

  fansupper: function () {
    wx.showNavigationBarLoading()
    wx.showLoading({
      title: "刷新中"
    });
    this.getFansData(function () {
      wx.hideLoading();
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 2000
      });
      wx.hideNavigationBarLoading(); wx.stopPullDownRefresh();
    });

    console.log("fansupper");
    
  },
 
  //使用本地 fake 数据实现刷新效果
  getData: function (cb) {
    var _this = this;
    var sql = "select a.nick_name,a.head_img,b.id,b.unionid,b.dynamic_txt,b.dynamic_img,b.location,b.lat,b.lng,b.createtime,b.comments,b.praises from user a inner join star_dynamic b on a.unionid = b.unionid and a.unionid='" + this.data.userInfo.unionid + "'  order by b.createtime desc limit 10";
   
    console.log(sql);
    wx.request({
      url: 'https://www.dpsoft.top/db.jsp', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        sql: sql
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        console.log(res.data);

        if ("ok" == res.data.status) {
          var feed_data = res.data.data;
          for (var x in feed_data) {
            feed_data[x].dynamic_txt = decodeURI(feed_data[x].dynamic_txt);
            if (feed_data[x].dynamic_img != null && feed_data[x].dynamic_img.length > 0)
              feed_data[x].imgarray = feed_data[x].dynamic_img.split(",");
            if (feed_data[x].comments != null && feed_data[x].comments.length > 0) {
              feed_data[x].commentArray = JSON.parse(decodeURI(feed_data[x].comments));
            } else {
              feed_data[x].commentArray = [];
            }

            if (feed_data[x].praises != null && feed_data[x].praises.length > 0) {
              feed_data[x].praiseArray = JSON.parse(feed_data[x].praises);
            } else {
              feed_data[x].praiseArray = [];
            }
            feed_data[x].createtime = this.formatdate(feed_data[x].createtime);

          }
          _this.setData({
            feed: feed_data,
            feed_length: feed_data.length
          });

          typeof cb == "function" && cb();



        } else {

        }
      }
    });
  },
  

  //使用本地 fake 数据实现继续加载效果
  nextLoad: function () {

    wx.showLoading({
      title: "加载中"
    });

    var sql = "select a.nick_name,a.head_img,b.id,b.unionid,b.dynamic_txt,b.dynamic_img,b.location,b.lat,b.lng,b.createtime,b.comments,b.praises from user a inner join star_dynamic b on a.unionid = b.unionid and a.unionid='" + this.data.userInfo.unionid + "'  order by b.createtime desc limit " + this.data.feed_length + ", 10";


    console.log(sql);

    wx.request({
      url: 'https://www.dpsoft.top/db.jsp', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        sql: sql
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        console.log(res.data);
        wx.hideLoading();
        if ("ok" == res.data.status) {
          var next_data = res.data.data;
          for (var x in next_data) {
            next_data[x].dynamic_txt = decodeURI(next_data[x].dynamic_txt);
            if (next_data[x].dynamic_img != null && next_data[x].dynamic_img.length > 0)
              next_data[x].imgarray = next_data[x].dynamic_img.split(",");
            if (next_data[x].comments != null && next_data[x].comments.length > 0) {
              next_data[x].commentArray = JSON.parse(decodeURI(next_data[x].comments));
            } else {
              next_data[x].commentArray = [];
            }
            if (next_data[x].praises != null && next_data[x].praises.length > 0) {
              next_data[x].praiseArray = JSON.parse(next_data[x].praises);
            } else {
              next_data[x].praiseArray = [];
            }
            next_data[x].createtime = this.formatdate(next_data[x].createtime);
          }
          this.setData({
            feed: this.data.feed.concat(next_data),
            feed_length: this.data.feed_length + next_data.length
          });
          wx.showToast({
            title: '加载成功',
            icon: 'success',
            duration: 2000
          });
        } else {

        }
      }
    });
  },
  tocomment: function (event) {
    var _this = this;
    console.log(event.currentTarget.dataset.idx);
    var idx = event.currentTarget.dataset.idx;
    var repliername = event.currentTarget.dataset.repliername;
    var replierunionid = event.currentTarget.dataset.replierunionid;
    var sortid = event.currentTarget.dataset.sortid;
    if (null != repliername && null != replierunionid) {
      if (replierunionid == app.globalData.unionid) {
        wx.showActionSheet({
          itemList: ['删除我的评论'],
          success: function (res) {
            console.log(res.tapIndex)
            if (0 == res.tapIndex) {
              for (var x in _this.data.feed[idx].commentArray) {
                if (_this.data.feed[idx].commentArray[x].sortid == sortid) {
                  _this.data.feed[idx].commentArray.splice(x, 1);
                  _this.uptcomment(idx);
                  break;
                }
              }
            }
          },
          fail: function (res) {
            console.log(res.errMsg)
          }
        })
        return;
      }


      this.data.feed[idx].replier = { name: repliername, unionid: replierunionid };
      this.data.feed[idx].commenttag = '回复' + repliername;
    } else {
      this.data.feed[idx].commenttag = '评论';
    }
    this.data.feed[idx].commentflag = true;
    this.setData({
      feed: this.data.feed
    });
  },
  docomment: function (event) {
    var _this = this;
    var value = event.detail.value;
    console.log(value);
    var idx = event.currentTarget.dataset.idx;

    this.data.feed[idx].commentflag = false;

    this.data.feed[idx].commentArray.push({ sortid: this.data.feed[idx].commentArray.length, commentor: { name: app.globalData.userInfo.nickName, unionid: app.globalData.unionid }, replier: this.data.feed[idx].replier, commenttxt: event.detail.value });

    this.uptcomment(idx);

    this.insertmsg({ msg_type: this.data.feed[idx].replier != null ? 1 : 0, dynamic_id: this.data.feed[idx].id, msg_unionid: app.globalData.unionid, status: 0, unionid: this.data.feed[idx].replier != null ? this.data.feed[idx].replier.unionid : this.data.feed[idx].unionid, msg: value });






  },
  insertmsg: function (msg) {
    var _this = this;

    var sql = "insert user_msg (msg_type,dynamic_id,msg_unionid,status,createtime,unionid,msg) values(" + msg.msg_type + "," + msg.dynamic_id + ",'" + msg.msg_unionid + "'," + msg.status + ",now(),'" + msg.unionid + "','" + encodeURI(msg.msg) + "')";

    console.log(sql);

    wx.request({
      url: 'https://www.dpsoft.top/db.jsp', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        sql: sql
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        console.log(res.data);

        if ("ok" == res.data.status) {



        } else {
          wx.showToast({
            title: '失败，请重试',
            icon: 'success',
            duration: 2000
          });
        }
      }
    });
  },
  uptcomment: function (idx) {
    var _this = this;
    var commentJson = JSON.stringify(this.data.feed[idx].commentArray);
    commentJson = commentJson.replace("'", "\\'");
    var sql = "update star_dynamic set comments='" + encodeURI(commentJson) + "' where id = " + this.data.feed[idx].id;

    console.log(sql);

    wx.request({
      url: 'https://www.dpsoft.top/db.jsp', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        sql: sql
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        console.log(res.data);

        if ("ok" == res.data.status) {

          _this.setData({
            feed: this.data.feed
          });

        } else {
          wx.showToast({
            title: '失败，请重试',
            icon: 'success',
            duration: 2000
          });
        }
      }
    });
  },
  formatdate: function (createtime) {
    var createdate = new Date(createtime);
    var nowdate = new Date();
    var hour = createdate.getHours();
    var minute = createdate.getMinutes();

    var nowyear = nowdate.getFullYear();
    var nowmonth = nowdate.getMonth();
    var nowday = nowdate.getDate();

    var createyear = createdate.getFullYear();
    var createmonth = createdate.getMonth();
    var createday = createdate.getDate();

    if (nowyear == createyear) {
      if (nowmonth = createmonth) {
        if (nowday == createday) {
          return "今天 " + hour + ":" + minute;
        } else if ((nowday - createday) == 1) {
          return "昨天 " + hour + ":" + minute;
        } else if ((nowday - createday) == 2) {
          return "前天 " + hour + ":" + minute;
        } else {
          return createday + "日 " + hour + ":" + minute;
        }
      } else {
        return createmonth + "月" + createday + "日 " + hour + ":" + minute;
      }
    } else {
      return createyear + "年" + createmonth + "月" + createday + "日 " + hour + ":" + minute;
    }
  },
  nocomment: function (event) {
    var _this = this;
    setTimeout(function () {
      if (!_this.data.commentfocus) {

        console.log(event.detail.value);
        var idx = event.currentTarget.dataset.idx;
        _this.data.feed[idx].commentflag = false;
        _this.setData({
          feed: _this.data.feed
        });
      }
      _this.data.commentfocus = false;
    }, 100);
  },
  focuscomment: function () {
    var _this = this;
    this.data.commentfocus = true;
    setTimeout(function () {
      _this.data.commentfocus = false;
    }, 100);
  },
  onPraise: function (event) {
    var _this = this;
    var idx = event.currentTarget.dataset.idx;

    var hasPraise = false;
    for (var x in this.data.feed[idx].praiseArray) {
      if (app.globalData.unionid == this.data.feed[idx].praiseArray[x].unionid) {
        hasPraise = true;
        this.data.feed[idx].praiseArray.splice(x, 1);
        break;
      }
    }


    if (!hasPraise) {

      this.data.feed[idx].praiseArray.push({ name: app.globalData.userInfo.nickName, unionid: app.globalData.unionid });
      this.insertmsg({ msg_type: 2, dynamic_id: this.data.feed[idx].id, msg_unionid: app.globalData.unionid, status: 0, unionid: this.data.feed[idx].unionid, msg: '' });
    }


    var praiseJson = JSON.stringify(this.data.feed[idx].praiseArray);
    praiseJson = praiseJson.replace("'", "\\'");
    var sql = "update star_dynamic set praises='" + praiseJson + "' where id = " + this.data.feed[idx].id;
    console.log(sql);

    wx.request({
      url: 'https://www.dpsoft.top/db.jsp', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        sql: sql
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        console.log(res.data);

        if ("ok" == res.data.status) {

          _this.setData({
            feed: this.data.feed
          });

        } else {
          wx.showToast({
            title: '失败，请重试',
            icon: 'success',
            duration: 2000
          });
        }
      }
    });



  },

  onFollow: function (e) {
    var _this = this;
    var idx = e.currentTarget.dataset.idx;
    var sql = "insert user_follow (unionid,followid) values('" + app.globalData.unionid + "','" + e.currentTarget.dataset.unionid + "')"
    console.log(sql);

    wx.request({
      url: 'https://www.dpsoft.top/db.jsp', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        sql: sql
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        console.log(res.data);

        if ("ok" == res.data.status) {
          _this.data.feed[idx].followid = 'true';
          _this.setData({
            feed: _this.data.feed
          });
          wx.showToast({
            title: '已关注',
            icon: 'success',
            duration: 2000
          });

        } else {
          wx.showToast({
            title: '失败，请重试',
            icon: 'fail',
            duration: 2000
          });
        }
      }
    });
  },
  onPreviewImg: function (e) {
    var idx = e.currentTarget.dataset.idx;
    var imgindex = e.currentTarget.dataset.imgindex;
    var imgarray = this.data.feed[idx].imgarray;
    var previewarray = [];
    for (var x in imgarray) {
      previewarray.push('http://www.dpsoft.top/' + imgarray[x]);
    }
    wx.previewImage({
      current: previewarray[imgindex], // 当前显示图片的http链接
      urls: previewarray // 需要预览的图片http链接列表
    })
  },
  onDeldynamic: function (e) {
    var _this = this;
    var idx = e.currentTarget.dataset.idx;
    if (this.data.feed[idx].unionid == app.globalData.unionid) {
      wx.showActionSheet({
        itemList: ['删除我的评论'],
        success: function (res) {
          console.log(res.tapIndex)
          if (0 == res.tapIndex) {
            var id = _this.data.feed[idx].id;
            var sql = "delete from star_dynamic where id=" + id;

            console.log(sql);

            wx.request({
              url: 'https://www.dpsoft.top/db.jsp', //仅为示例，并非真实的接口地址
              method: 'POST',
              data: {
                sql: sql
              },
              header: {
                'content-type': 'application/json' // 默认值
              },
              success: res => {
                console.log(res.data);

                if ("ok" == res.data.status) {
                  _this.data.feed.splice(idx, 1);

                  _this.setData({
                    feed: _this.data.feed
                  });


                } else {
                  wx.showToast({
                    title: '失败，请重试',
                    icon: 'fail',
                    duration: 2000
                  });
                }
              }
            });
          }
        },
        fail: function (res) {
          console.log(res.errMsg)
        }
      });

    }




  },


  getFollowData:function(cb){
    var _this = this;
    var sql = "select a.unionid,a.nick_name,a.head_img,a.occupation,a.star_state,b.id from user a,user_follow b where a.unionid = b.followid and b.unionid = '" + this.data.userInfo.unionid + "'";

    console.log(sql);
    wx.request({
      url: 'https://www.dpsoft.top/db.jsp', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        sql: sql
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        console.log(res.data);

        if ("ok" == res.data.status) {
          var followman = res.data.data;
          
          _this.setData({
            followman: followman
          });

          typeof cb == "function" && cb();



        } else {

        }
      }
    });
  },

  getFansData: function (cb) {
    var _this = this;
    var sql = "select a.unionid,a.nick_name,a.head_img,a.occupation,a.star_state from user a,user_follow b where a.unionid = b.unionid and b.followid = '" + this.data.userInfo.unionid + "'";

    console.log(sql);
    wx.request({
      url: 'https://www.dpsoft.top/db.jsp', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        sql: sql
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        console.log(res.data);

        if ("ok" == res.data.status) {
          var fans = res.data.data;

          _this.setData({
            fans: fans
          });

          typeof cb == "function" && cb();



        } else {

        }
      }
    });
  },
  onCancelFollow:function(e){
    var _this = this;
    var idx = e.currentTarget.dataset.idx;
    var id = e.currentTarget.dataset.id;
   
    var sql = "delete from user_follow where id="+id;
    console.log(sql);

    wx.request({
      url: 'https://www.dpsoft.top/db.jsp', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        sql: sql
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        console.log(res.data);

        if ("ok" == res.data.status) {
          _this.data.followman.splice(idx, 1);
          _this.setData({
            followman: _this.data.followman
          });
          wx.showToast({
            title: '已取消关注',
            icon: 'success',
            duration: 2000
          });

        } else {
          wx.showToast({
            title: '失败，请重试',
            icon: 'fail',
            duration: 2000
          });
        }
      }
    });


  },
  gotoUser:function(){
    wx.navigateTo({
      url: '/pages/more/more'
    })
  },
  openmap: function (e) {
    var lat = e.currentTarget.dataset.lat;
    var lng = e.currentTarget.dataset.lng;
    wx.navigateTo({ url: "/example/map/map?latitude=" + lat + "&longitude=" + lng });
  }

})